package com.starhub.domain.knowledge.controller;

import com.starhub.application.collection.dto.MetaDataLinkDto;
import com.starhub.application.rag.vo.SegmentVo;
import com.starhub.common.bean.ResultResp;
import com.starhub.common.security.util.SecurityUtils;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.domain.knowledge.dto.KnowledgeItemDto;
import com.starhub.domain.knowledge.result.KnowledgeItemsSearchResult;
import com.starhub.domain.knowledge.service.KnowledgeMetaDataService;
import com.starhub.domain.knowledge.service.KnowledgeService;
import com.starhub.domain.knowledge.vo.KnowledgeBaseVo;
import com.starhub.domain.knowledge.vo.KnowledgeCollectionVo;
import com.starhub.domain.knowledge.vo.KnowledgeItemVo;
import com.starhub.utils.Util;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 知识库数据接口
 * @version: V1.0
 * @author: liuhf
 * @time 2025-06-05
 */
@Slf4j
@RestController
@RequestMapping("/api/starhub/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;
    
    @Autowired
    private KnowledgeMetaDataService knowledgeMetaDataService;

    /**
     * 创建知识条目
     */
    @PostMapping("/item/create")
    public ResultResp<String> createKnowledgeItem(@RequestBody KnowledgeItemDto knowledgeItem) {
        try {
            LoginUser user = SecurityUtils.getCurrentUser();
            knowledgeItem.setCreatorId(Util.getLongValue(user.getUserId()));
            String id = knowledgeService.createKnowledgeItem(knowledgeItem, true);
            return ResultResp.success(id);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 更新知识条目
     */
    @PostMapping("/item/update")
    public ResultResp<Boolean> updateKnowledgeItem(@RequestBody KnowledgeItemDto knowledgeItem) {
        try {
            boolean result = knowledgeService.updateKnowledgeItem(knowledgeItem);
            return ResultResp.success(result);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 删除知识条目
     */
    @PostMapping("/item/delete/{id}")
    public ResultResp<Boolean> deleteKnowledgeItem(@PathVariable Long id) {
        try {
            boolean result = knowledgeService.deleteKnowledgeItem(id);
            return ResultResp.success(result);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 获取知识库信息
     */
    @GetMapping("/base/get/{id}")
    public ResultResp<KnowledgeBaseVo> getKnowledgeBaseById(@PathVariable Long id) {
        try {
            KnowledgeBaseVo knowledgeBase = knowledgeService.getKnowledgeBaseById(id);
            return ResultResp.success(knowledgeBase);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 获取知识库表信息
     */
    @GetMapping("/collection/get/{id}")
    public ResultResp<KnowledgeCollectionVo> getKnowledgeCollectionById(@PathVariable Long id) {
        try {
            KnowledgeCollectionVo collection = knowledgeService.getKnowledgeCollectionById(id);
            return ResultResp.success(collection);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 获取知识条目信息
     */
    @GetMapping("/item/get/{id}")
    public ResultResp<KnowledgeItemVo> getKnowledgeItemById(@PathVariable Long id) {
        try {
            KnowledgeItemVo item = knowledgeService.getKnowledgeItemById(id);
            return ResultResp.success(item);
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 分页查询知识条目
     * 
     * @param collectionId 知识库表ID
     * @param current 当前页码
     * @param size 每页大小
     * @param keyword 搜索关键词（可选）
     * @return 分页结果
     */
    @GetMapping("/item/search")
    public ResultResp<KnowledgeItemsSearchResult> pageKnowledgeItems(
            @RequestParam Long collectionId,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String keyword) {
        try {
            return ResultResp.success(knowledgeService.pageKnowledgeItems(collectionId, current, size, keyword));
        } catch (Exception e) {
            log.error("分页查询知识条目失败", e);
            return ResultResp.fail(e.getMessage());
        }
    }

    /**
     * 在指定知识库表中检索文本
     * @param collectionId 知识库表ID
     * @param queryText 检索文本
     * @param topK 返回最相似的前K条记录
     * @return 检索结果列表
     */
    @GetMapping("/segment/search")
    public ResultResp<List<SegmentVo>> searchKnowledgeItems(
            @RequestParam Long collectionId,
            @RequestParam String queryText,
            @RequestParam(defaultValue = "5") Integer topK,
            @RequestParam(defaultValue = "0.5") Double minScore) {
        try {
            return ResultResp.success(knowledgeService.searchSegments(collectionId, queryText, topK, minScore));
        } catch (Exception e) {
            return ResultResp.fail(e.getMessage());
        }
    }


    /**
     * 添加目标链接数据
     */
    @PostMapping("/link/add")
    public ResultResp<Boolean> addTargetLinkData(@RequestBody MetaDataLinkDto metaDataLinkDto) {
        return ResultResp.success(knowledgeMetaDataService.addTargetLinkData(metaDataLinkDto));
    }

    /**
     * 更新目标链接数据
     */
    @PostMapping("/link/update")
    public ResultResp<Boolean> updateTargetLinkData(@RequestBody MetaDataLinkDto metaDataLinkDto) {
        return ResultResp.success(knowledgeMetaDataService.updateTargetLinkData(metaDataLinkDto));
    }

    /**
     * 删除目标链接数据
     */
    @PostMapping("/link/remove")
    public ResultResp<Boolean> deleteTargetLinkData(@RequestBody MetaDataLinkDto metaDataLinkDto) {
        return ResultResp.success(knowledgeMetaDataService.removeTargetLinkData(metaDataLinkDto));
    }

    /**
     * 删除所有目标链接数据
     */
    @PostMapping("/link/remove/all")
    public ResultResp<Boolean> deleteAllTargetLinkData(@RequestBody MetaDataLinkDto metaDataLinkDto) {
        return ResultResp.success(knowledgeMetaDataService.removeAllTargetLinkData(metaDataLinkDto));
    }
} 